import os
from .base import BaseSelectable, INDICATOR_CHAR


class PipeSelectable(BaseSelectable):
    """
    A selectable using a pipe underneath, prolly faster than a socket but
    doesn't work on Windows.
    """
    
    def __init__(self):
        super(PipeSelectable, self).__init__()
        self.read_pipe, self.write_pipe = os.pipe()
        self._is_set = False
        
    def __del__(self):
        # gotta close these file descriptors manually, since they're just
        # integers, they don't get garbage collected or anything
        os.close(self.read_pipe)
        os.close(self.write_pipe)
    
    def set(self):
        with self._lock:
            if not self._is_set:
                assert(os.write(self.write_pipe, INDICATOR_CHAR) == 1)
                assert(self.wait(0.001))
                self._is_set = True
    
    def is_set(self):
        return self._is_set
    
    def clear(self):
        with self._lock:
            if self._is_set:
                assert(os.read(self.read_pipe, 1) == INDICATOR_CHAR)
                assert(not self.wait(0.001))
                self._is_set = False
            
    def fileno(self):
        return self.read_pipe